<?
require_once(dirname(__FILE__) . '/../../classes/report_interface.inc.php');

abstract class LoggerModulePopularityHitsReportBaseClass 
{
    protected $database;

    public function __construct(LoggerDatabase $database) 
    {
        $this->database = $database;
    }
    

    protected function GetData($date1, $date2, $where, $start, $count)
    {
        $dirsSelect = '`d`.`id`, DATE_FORMAT(`d`.`time`, \'%d.%m.%Y\') AS `date`, DATE_FORMAT(`d`.`time`, \'%H:%i:%s\') AS `time`, `d`.`visitor`, `d`.`session`, ';
        $dirsJoin = '';

        for ($i = 1; $i <= 3; $i++)
        {
            $dirsSelect .= '`d`.`dir'.$i.'`, `s'.$i.'`.`string` AS `dir'.$i.'Str`, ';
            $dirsJoin .= 'LEFT JOIN `[PREF]module_popularity_strings` `s'.$i.'` ON `s'.$i.'`.`id`=`d`.`dir'.$i.'` ';
        }
        $dirsSelect .= '`f`.`string` AS `fileStr`, ';
        $dirsSelect .= '`q`.`string` AS `queryStr`, ';
        $dirsSelect .= '`t`.`string` AS `titleStr` ';
        $dirsJoin .= 'LEFT JOIN `[PREF]module_popularity_strings` `f` ON `f`.`id`=`d`.`file` ';
        $dirsJoin .= 'LEFT JOIN `[PREF]module_popularity_strings` `q` ON `q`.`id`=`d`.`query` ';
        $dirsJoin .= 'LEFT JOIN `[PREF]module_popularity_strings` `t` ON `t`.`id`=`d`.`title` ';

        $date1 = '\'' . mysql_escape_string($date1) . '\'';
        $date2 = '\'' . mysql_escape_string($date2) . '\'';

        $SelectSQL = 'SELECT '.$dirsSelect.' ';
        $SelectSQL .= 'FROM `[PREF]module_popularity` `d` ';
        $SelectSQL .= $dirsJoin;
        $SelectSQL .= 'WHERE '.$where.' AND `d`.`time`>='.$date1.' AND `d`.`time`<'.$date2.' + INTERVAL 1 DAY ';
        $SelectSQL .= 'ORDER BY `d`.`time`, `d`.`id` ';
        $SelectSQL .= 'LIMIT '.$start.','.$count;

        $data = array();
        $result = $this->database->Query($SelectSQL);
        if (!$result)
             trigger_error('Database Error: ' . $this->database->Error(), E_USER_ERROR);
        while ($row = $this->database->FetchAssoc($result))
        {
            $sourceLink = false;
            $SelectSQL = 'SELECT `l`.`scheme`, `s`.`string` AS `serverStr`, `p`.`string` AS `pathStr`, `q`.`string` AS `queryStr` ';
            $SelectSQL .= 'FROM `[PREF]module_sources_links` `l` ';
            $SelectSQL .= 'LEFT JOIN `[PREF]module_sources_strings` `s` ON `s`.`id`=`l`.`serv` ';
            $SelectSQL .= 'LEFT JOIN `[PREF]module_sources_strings` `p` ON `p`.`id`=`l`.`path` ';
            $SelectSQL .= 'LEFT JOIN `[PREF]module_sources_strings` `q` ON `q`.`id`=`l`.`query` ';
            $SelectSQL .= 'WHERE `log`='.intval($row['id']);
            $resultLink = $this->database->Query($SelectSQL);
            if (!$resultLink)
                 trigger_error('Database Error: ' . $this->database->Error(), E_USER_ERROR);
            if ($rowLink = $this->database->FetchAssoc($resultLink))
                $sourceLink = $rowLink;

            $sourceSearch = false;
            $SelectSQL = 'SELECT `s`.`engine`, `s`.`page`, `t`.`string` AS `textStr` ';
            $SelectSQL .= 'FROM `[PREF]module_sources_search` `s` ';
            $SelectSQL .= 'LEFT JOIN `[PREF]module_sources_strings` `t` ON `t`.`id`=`s`.`text` ';
            $SelectSQL .= 'WHERE `log`='.intval($row['id']);
            $resultSearch = $this->database->Query($SelectSQL);
            if (!$resultSearch)
                 trigger_error('Database Error: ' . $this->database->Error(), E_USER_ERROR);
            if ($rowSearch = $this->database->FetchAssoc($resultSearch))
                $sourceSearch = $rowSearch;

            $visitorName = false;
            $SelectSQL = 'SELECT `name` ';
            $SelectSQL .= 'FROM `[PREF]visitors` ';
            $SelectSQL .= 'WHERE `id`='.intval($row['visitor']);
            $resultVisitor = $this->database->Query($SelectSQL);
            if (!$resultVisitor)
                 trigger_error('Database Error: ' . $this->database->Error(), E_USER_ERROR);
            if ($rowVisitor = $this->database->FetchAssoc($resultVisitor))
                $visitorName = $rowVisitor;

            $data[] = array(
                'hit' => $row,
                'sourceLink' => $sourceLink,
                'sourceSearch' => $sourceSearch,
                'visitorName' => $visitorName
            );
        }
        $this->database->FreeResult($result);
        return $data;
    }
    
    protected function DetectModeReport($date1, $date2, $params)
    {
        if ($params['by'] == 'title')
        {
            $titleId = intval($params['id']);

            $reportName = 'Просмотры по заголовку';

            $SelectSQL = 'SELECT `string` FROM `[PREF]module_popularity_strings` WHERE `id`=' . intval($titleId);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $reportName .= ' "' . $row['string'] . '"';
            }

            $whereStr = '`d`.`title`='.intval($titleId);
        }
        elseif ($params['by'] == 'visitor')
        {
            $visitorId = intval($params['id']);

            $reportName = 'Просмотры по посетителю №' . $visitorId;
            $SelectSQL = 'SELECT `name` FROM `[PREF]visitors` WHERE `id`=' . intval($visitorId);
            $result = $this->database->Query($SelectSQL);
            if ($result)
            {
                $row = $this->database->FetchAssoc($result);
                if ($row)
                    $reportName .= ' (' . $row['name'] . ')';
            }
            $whereStr = '`d`.`visitor`='.intval($visitorId);
        }
        elseif ($params['by'] == 'session')
        {
            $sessionId = intval($params['id']);
            
            $reportName = 'Просмотры по визиту №' . $sessionId;
            $whereStr = '`d`.`session`='.intval($sessionId);
        }
        elseif ($params['by'] == 'link')
        {
            $dirs = explode(',', $params['dirs']);
            $file = intval($params['file']);
            $query = intval($params['query']);
            
            list($url, $urlHuman) = $this->GetUrlByIds($dirs, $file, $query);

            $reportName = 'Просмотры по ссылке ' . htmlspecialchars($urlHuman);
            $arWhereStr = array();
            for ($i = 0; $i < 3; $i++)
            if (isset($dirs[$i]))
                $arWhereStr[] = '`d`.`dir'.($i+1).'`='.intval($dirs[$i]);
            $arWhereStr[] = '`d`.`file`='.$file;
            $arWhereStr[] = '`d`.`query`='.$query;

            $whereStr = implode(' AND ', $arWhereStr);
        }
        elseif ($params['by'] == 'search')
        {
            $searchId = intval($params['id']);

            $reportName = 'Просмотры по поисковому запросу';

            $SelectSQL = 'SELECT `string` FROM `[PREF]module_sources_strings` WHERE `id`=' . intval($searchId);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $reportName .= ' "' . $row['string'] . '"';
            }

            $date1Escaped = '\'' . mysql_escape_string($date1) . '\'';
            $date2Escaped = '\'' . mysql_escape_string($date2) . '\'';

            $arWhereStr = array();
            $SelectSQL = 'SELECT `log` FROM `[PREF]module_sources_search` ';
            $SelectSQL .= 'WHERE `date`>='.$date1Escaped.' AND `date`<='.$date2Escaped.' AND `text`=' . $searchId;

            $whereStr = '`d`.`id` IN (' . $SelectSQL . ')';
        }
        elseif ($params['by'] == 'engine')
        {
            $engine = $params['engine'];
            
            $reportName = 'Просмотры по переходу с поисковика "' . $engine . '"';
            $engine = '\'' . mysql_escape_string($engine) . '\'';

            $date1Escaped = '\'' . mysql_escape_string($date1) . '\'';
            $date2Escaped = '\'' . mysql_escape_string($date2) . '\'';

            $arWhereStr = array();
            $SelectSQL = 'SELECT `log` FROM `[PREF]module_sources_search` ';
            $SelectSQL .= 'WHERE `date`>='.$date1Escaped.' AND `date`<='.$date2Escaped.' AND `engine`=' . $engine;

            $whereStr = '`d`.`id` IN (' . $SelectSQL . ')';
        }
        elseif ($params['by'] == 'engineaq')
        {
            $engine = $params['engine'];
            $text = intval($params['text']);

            $SelectSQL = 'SELECT `string` FROM `[PREF]module_sources_strings` WHERE `id`=' . intval($text);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $textStr = $row['string'];
            }
            $reportName = 'Просмотры  по поисковому запросу "' . $textStr . '" с поисковика "' . $engine . '"';
            $engine = '\'' . mysql_escape_string($engine) . '\'';

            $date1Escaped = '\'' . mysql_escape_string($date1) . '\'';
            $date2Escaped = '\'' . mysql_escape_string($date2) . '\'';

            $arWhereStr = array();
            $SelectSQL = 'SELECT `log` FROM `[PREF]module_sources_search` ';
            $SelectSQL .= 'WHERE `date`>='.$date1Escaped.' AND `date`<='.$date2Escaped.' ';
            $SelectSQL .= 'AND `engine`=' . $engine.' AND `text`=' . $text;

            $whereStr = '`d`.`id` IN (' . $SelectSQL . ')';
        }
        elseif ($params['by'] == 'enginebq')
        {
            $engine = $params['engine'];
            $page = intval($params['page']);
            $text = intval($params['text']);

            $SelectSQL = 'SELECT `string` FROM `[PREF]module_sources_strings` WHERE `id`=' . intval($text);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $textStr = $row['string'];
            }
            $reportName = 'Просмотры  по поисковому запросу "' . $textStr . '" с поисковика "' . $engine . '" на странице ' . $page;
            $engine = '\'' . mysql_escape_string($engine) . '\'';


            $date1Escaped = '\'' . mysql_escape_string($date1) . '\'';
            $date2Escaped = '\'' . mysql_escape_string($date2) . '\'';

            $arWhereStr = array();
            $SelectSQL = 'SELECT `log` FROM `[PREF]module_sources_search` ';
            $SelectSQL .= 'WHERE `date`>='.$date1Escaped.' AND `date`<='.$date2Escaped.' ';
            $SelectSQL .= 'AND `engine`=' . $engine.' AND `page`=' . $page.' AND `text`=' . $text;

            $whereStr = '`d`.`id` IN (' . $SelectSQL . ')';
        }
        elseif ($params['by'] == 'ref')
        {
            $scheme = $params['scheme'];
            $serv = intval($params['serv']);
            $path = intval($params['path']);
            $query = intval($params['query']);

            list($ref, $refHuman) = $this->GetRefByIds($scheme, $serv, $path, $query);
            $scheme = '\'' . mysql_escape_string($scheme) . '\'';

            $reportName = 'Просмотры по переходу со ссылки ' . $ref;

            $date1Escaped = '\'' . mysql_escape_string($date1) . '\'';
            $date2Escaped = '\'' . mysql_escape_string($date2) . '\'';

            $arWhereStr = array();
            $SelectSQL = 'SELECT `log` FROM `[PREF]module_sources_links` ';
            $SelectSQL .= 'WHERE `date`>='.$date1Escaped.' AND `date`<='.$date2Escaped.' AND ';
            $SelectSQL .= ' `scheme`='.$scheme.' AND `serv`='.$serv.' AND `path`='.$path.' AND `query`='.$query;

            $whereStr = '`d`.`id` IN (' . $SelectSQL . ')';
        }
        elseif ($params['by'] == 'refs')
        {
            $servId = intval($params['id']);

            $SelectSQL = 'SELECT `string` FROM `[PREF]module_sources_strings` WHERE `id`=' . intval($servId);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $servStr = $row['string'];
            }

            $reportName = 'Просмотры по переходу с сервера "' . $servStr . '"';

            $date1Escaped = '\'' . mysql_escape_string($date1) . '\'';
            $date2Escaped = '\'' . mysql_escape_string($date2) . '\'';

            $arWhereStr = array();
            $SelectSQL = 'SELECT `log` FROM `[PREF]module_sources_links` ';
            $SelectSQL .= 'WHERE `date`>='.$date1Escaped.' AND `date`<='.$date2Escaped.' AND `serv`='.$servId;

            $whereStr = '`d`.`id` IN (' . $SelectSQL . ')';

        }
        elseif ($params['by'] == 'browser')
        {
            $browserId = intval($params['browser']);

            $SelectSQL = 'SELECT `string` FROM `[PREF]module_browsers_strings` WHERE `id`=' . intval($browserId);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $browserStr = $row['string'];
            }

            $reportName = 'Просмотры по браузеру "' . $browserStr . '"';

            $date1Escaped = '\'' . mysql_escape_string($date1) . '\'';
            $date2Escaped = '\'' . mysql_escape_string($date2) . '\'';

            $arWhereStr = array();
            $SelectSQL = 'SELECT `log` FROM `[PREF]module_browsers` ';
            $SelectSQL .= 'WHERE `date`>='.$date1Escaped.' AND `date`<='.$date2Escaped.' AND `browser`='.$browserId;
 
//          Виснет в состоянии "Sending data"
//          $whereStr = '`d`.`id` IN (' . $SelectSQL . ')';

            $logs = array(0);
            $result = $this->database->Query($SelectSQL);
            while($result && ($row = $this->database->FetchAssoc($result)))
                $logs[] = $row['log'];
            $whereStr = '`d`.`id` IN (' . implode(',', $logs) . ')';
        }
        elseif ($params['by'] == 'browserver')
        {
            $browserId  = intval($params['browser']);
            $verId      = intval($params['ver']);

            $SelectSQL = 'SELECT `string` FROM `[PREF]module_browsers_strings` WHERE `id`=' . intval($browserId);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $browserStr = $row['string'];
            }

            $SelectSQL = 'SELECT `string` FROM `[PREF]module_browsers_strings` WHERE `id`=' . intval($verId);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $verStr = $row['string'];
            }

            $reportName = 'Просмотры по браузеру "' . $browserStr . ' ' . $verStr . '"';


            $date1Escaped = '\'' . mysql_escape_string($date1) . '\'';
            $date2Escaped = '\'' . mysql_escape_string($date2) . '\'';

            $arWhereStr = array();
            $SelectSQL = 'SELECT `log` FROM `[PREF]module_browsers` ';
            $SelectSQL .= 'WHERE `date`>='.$date1Escaped.' AND `date`<='.$date2Escaped.' AND `browser`='.$browserId.' AND `ver`='.$verId;
 
//          Виснет в состоянии "Sending data"
//          $whereStr = '`d`.`id` IN (' . $SelectSQL . ')';

            $logs = array(0);
            $result = $this->database->Query($SelectSQL);
            while($result && ($row = $this->database->FetchAssoc($result)))
                $logs[] = $row['log'];
            $whereStr = '`d`.`id` IN (' . implode(',', $logs) . ')';
        }
        elseif ($params['by'] == 'platform')
        {
            $platformId = intval($params['platform']);

            $SelectSQL = 'SELECT `string` FROM `[PREF]module_platforms_strings` WHERE `id`=' . intval($platformId);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $platformStr = $row['string'];
            }

            $reportName = 'Просмотры по платформе "' . $platformStr . '"';

            $date1Escaped = '\'' . mysql_escape_string($date1) . '\'';
            $date2Escaped = '\'' . mysql_escape_string($date2) . '\'';

            $arWhereStr = array();
            $SelectSQL = 'SELECT `log` FROM `[PREF]module_platforms` ';
            $SelectSQL .= 'WHERE `date`>='.$date1Escaped.' AND `date`<='.$date2Escaped.' AND `platform`='.$platformId;
 
//          Виснет в состоянии "Sending data"
//          $whereStr = '`d`.`id` IN (' . $SelectSQL . ')';

            $logs = array(0);
            $result = $this->database->Query($SelectSQL);
            while($result && ($row = $this->database->FetchAssoc($result)))
                $logs[] = $row['log'];
            $whereStr = '`d`.`id` IN (' . implode(',', $logs) . ')';
        }
        elseif ($params['by'] == 'country')
        {
            $countryId = intval($params['country']);

            $SelectSQL = 'SELECT `string` FROM `[PREF]module_geo_strings` WHERE `id`=' . intval($platformId);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $platformStr = $row['string'];
            }

            $reportName = 'Просмотры по стране "' . $platformStr . '"';

            $date1Escaped = '\'' . mysql_escape_string($date1) . '\'';
            $date2Escaped = '\'' . mysql_escape_string($date2) . '\'';

            $arWhereStr = array();
            $SelectSQL = 'SELECT `log` FROM `[PREF]module_geo` ';
            $SelectSQL .= 'WHERE `date`>='.$date1Escaped.' AND `date`<='.$date2Escaped.' AND `country`='.$countryId;
 
//          Виснет в состоянии "Sending data"
//          $whereStr = '`d`.`id` IN (' . $SelectSQL . ')';

            $logs = array(0);
            $result = $this->database->Query($SelectSQL);
            while($result && ($row = $this->database->FetchAssoc($result)))
                $logs[] = $row['log'];
            $whereStr = '`d`.`id` IN (' . implode(',', $logs) . ')';
        }
        elseif ($params['by'] == 'city')
        {
            $countryId  = intval($params['country']);
            $cityId     = intval($params['city']);

            $SelectSQL = 'SELECT `string` FROM `[PREF]module_geo_strings` WHERE `id`=' . intval($countryId);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $countryStr = $row['string'];
            }

            $SelectSQL = 'SELECT `string` FROM `[PREF]module_geo_strings` WHERE `id`=' . intval($cityId);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $cityStr = $row['string'];
            }

            $reportName = 'Просмотры по городу "' . $cityStr . ' ' . $countryStr . '"';

            $city = '\'' . mysql_escape_string($city) . '\'';

            $date1Escaped = '\'' . mysql_escape_string($date1) . '\'';
            $date2Escaped = '\'' . mysql_escape_string($date2) . '\'';

            $arWhereStr = array();
            $SelectSQL = 'SELECT `log` FROM `[PREF]module_geo` ';
            $SelectSQL .= 'WHERE `date`>='.$date1Escaped.' AND `date`<='.$date2Escaped.' AND `country`='.$countryId.' AND `city`='.$cityId;
 
//          Виснет в состоянии "Sending data"
//          $whereStr = '`d`.`id` IN (' . $SelectSQL . ')';

            $logs = array(0);
            $result = $this->database->Query($SelectSQL);
            while($result && ($row = $this->database->FetchAssoc($result)))
                $logs[] = $row['log'];
            $whereStr = '`d`.`id` IN (' . implode(',', $logs) . ')';
        }
        else
            return false;

        return array(
            $reportName,
            $whereStr
        );
    }
    
    protected function ProcessData($data, $root)
    {
        $xml = $root->ownerDocument;
    
        $reportData = $xml->createElement('report_data');
        $root->appendChild($reportData);

        foreach($data as $row)
        {
            $dataRow = $xml->createElement('row');
            $reportData->appendChild($dataRow);
            list($url, $urlHuman) = $this->FormatUrlName($row['hit']);
            $dataRow->setAttribute('VID', $row['hit']['visitor']);
            $dataRow->setAttribute('SID', $row['hit']['session']);
            $dataRow->setAttribute('date', $row['hit']['date']);
            $dataRow->setAttribute('time', $row['hit']['time']);
            $dataRow->setAttribute('url', $url);
            $dataRow->setAttribute('urlHuman', $urlHuman);
            $dataRow->setAttribute('title', $row['hit']['titleStr']);
            $titleHuman = $row['hit']['titleStr'];
            if (function_exists('mb_strlen') && mb_strlen($titleHuman, 'UTF-8') > 100)
                $titleHuman = mb_substr($titleHuman, 0, 97, 'UTF-8') . '...';
            $dataRow->setAttribute('titleHuman', $titleHuman);
            if (is_array($row['sourceLink']))
            {
                $sourceLink = $xml->createElement('source_link');
                $dataRow->appendChild($sourceLink);
                list($url, $urlHuman) = $this->FormatUrlNameSimple($row['sourceLink']);
                $sourceLink->setAttribute('url', $url);
                $sourceLink->setAttribute('urlHuman', $urlHuman);
            }
            if (is_array($row['sourceSearch']))
            {
                $sourceSearch = $xml->createElement('source_search');
                $dataRow->appendChild($sourceSearch);
                $sourceSearch->setAttribute('engine', $row['sourceSearch']['engine']);
                $sourceSearch->setAttribute('page', $row['sourceSearch']['page']);
                $sourceSearch->setAttribute('text', $row['sourceSearch']['textStr']);
                $sourceSearch->setAttribute('text', $row['sourceSearch']['textStr']);
                $textHuman = $row['sourceSearch']['textStr'];
                if (function_exists('mb_strlen') && mb_strlen($textHuman, 'UTF-8') > 100)
                    $textHuman = mb_substr($textHuman, 0, 97, 'UTF-8') . '...';
                $sourceSearch->setAttribute('textHuman', $textHuman);
            }
            if (is_array($row['visitorName']))
            {
                $dataRow->setAttribute('VName', $row['visitorName']['name']);
            }
        }
    }
    
    protected function GetRefByIds($scheme, $serv, $path, $query)
    {
        $ref = $scheme . '://';
        $SelectSQL = 'SELECT `string` FROM `[PREF]module_sources_strings` WHERE `id`=' . intval($serv);
        $result = $this->database->Query($SelectSQL);
        if ($result && ($row = $this->database->FetchAssoc($result)))
        {
            $ref .= $row['string'];
        }
        if ($path)
        {
            $SelectSQL = 'SELECT `string` FROM `[PREF]module_sources_strings` WHERE `id`=' . intval($path);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $ref .= $row['string'];
            }
        }
        if ($query)
        {
            $SelectSQL = 'SELECT `string` FROM `[PREF]module_sources_strings` WHERE `id`=' . intval($query);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $ref .= $row['string'];
            }
        }
        
        $refHuman = $ref;
        if (strlen($refHuman) > 100)
            $refHuman = substr($refHuman, 0, 97) . '...';

        return array(
            $ref,
            $refHuman
        );
    }
    
    protected function GetUrlByIds($dirs, $file, $query)
    {
        $arValues = array();

        for ($i = 1; $i <= 3; $i++)
        {
            $arValues['dir' . $i] = $dirs[$i - 1];
            $arValues['dir' . $i . 'Str'] = '';
            $SelectSQL = 'SELECT `string` FROM `[PREF]module_popularity_strings` WHERE `id`=' . intval($dirs[$i - 1]);
            $result = $this->database->Query($SelectSQL);
            if ($result && ($row = $this->database->FetchAssoc($result)))
            {
                $arValues['dir' . $i . 'Str'] = $row['string'];
            }
        }

        $SelectSQL = 'SELECT `string` FROM `[PREF]module_popularity_strings` WHERE `id`=' . intval($file);
        $result = $this->database->Query($SelectSQL);
        if ($result && ($row = $this->database->FetchAssoc($result)))
        {
            $arValues['fileStr'] = $row['string'];
        }

        $SelectSQL = 'SELECT `string` FROM `[PREF]module_popularity_strings` WHERE `id`=' . intval($query);
        $result = $this->database->Query($SelectSQL);
        if ($result && ($row = $this->database->FetchAssoc($result)))
        {
            $arValues['queryStr'] = $row['string'];
        }

        return $this->FormatUrlName($arValues);
    }

    protected function FormatDirName($row)
    {
        $dirName = '';
        $arDirId = array();
        for ($i = 1; $i <= 5; $i++)
            if (isset($row['dir'.$i]))
            {
                $dirName .= '/' . $row['dir'.$i.'Str'];
                $arDirId[] = $row['dir'.$i];
            }
            else
                break;
        if (substr($dirName, -1) != '/')
            $dirName .= '/';

        return array(
            implode(',', $arDirId),
            $dirName
        );
    }

    protected function FormatUrlName($row)
    {
        
        $url = LoggerConfig::$myBaseUrl;
        $urlHuman = '';
        for ($i = 1; $i <= 5; $i++)
        {
            $url .= '/' . $row['dir'.$i.'Str'];        
            $urlHuman .= '/' . $row['dir'.$i.'Str'];

            if ($row['dir'.$i] == 0)
                break;
        }

        if (substr($url, -1) != '/')
        {
            $url .= '/';
            $urlHuman .= '/';
        }

        if (isset($row['fileStr']) && $row['fileStr'])
        {
            $url .= $row['fileStr'];
            $urlHuman .= $row['fileStr'];
        }
        if (isset($row['queryStr']) && $row['queryStr'])
        {
            $url .= '?' . $row['queryStr'];
            $urlHuman .= '?' . $row['queryStr'];
        }

        if (strlen($urlHuman) > 100)
            $urlHuman = substr($urlHuman, 0, 97) . '...';

        return array(
            $url,
            $urlHuman
        );
    }

    protected function FormatUrlNameSimple($row)
    {
        $url = $row['scheme'] . '://' . $row['serverStr'] . $row['pathStr'];
        if ($row['queryStr'] != '')
            $url .= '?' . $row['queryStr'];
        $urlHuman = $url;
        if (strlen($urlHuman) > 100)
            $urlHuman = substr($urlHuman, 0, 97) . '...';

        return array(
            $url,
            $urlHuman
        );
    }
}


class LoggerModulePopularityHitsReport extends LoggerModulePopularityHitsReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        $limit_start = 0;
        $limit_count = 100;

        $xml = $root->ownerDocument;

        $detectResult = $this->DetectModeReport($date1, $date2, $params);
        if (!is_array($detectResult))
            return false;

        list($reportName, $whereStr) = $detectResult;

        $name = $xml->createElement('report_name', $reportName);
        $root->appendChild($name);

        $SelectSQL = 'SELECT COUNT(*) AS `count`, MIN(`time`) as `minTime`, MAX(`time`) AS `maxTime` FROM `[PREF]module_popularity`';
        $result = $this->database->Query($SelectSQL);
        if($result && ($row = $this->database->FetchAssoc($result)))
        {
            if ($row['count'] == 0)
            {
                $empty = $xml->createElement('empty');
                $root->appendChild($empty);
            }
            else
            {
                $minTime = strtotime($row['minTime']);
                $maxTime = strtotime($row['maxTime']);
    
                if ($minTime > strtotime($date1) - 24*3600 || $maxTime < strtotime($date2) + 24*3600)
                {
                    $incomplete = $xml->createElement('incomplete');
                    $incomplete->setAttribute('minDate', date('d.m.Y', $minTime));
                    $incomplete->setAttribute('maxDate', date('d.m.Y', $maxTime));
                    $root->appendChild($incomplete);
                }
            }
        }

        $data = $this->GetData($date1, $date2, $whereStr, $limit_start, $limit_count);

        $this->ProcessData($data, $root);

        if (count($data) == $limit_count)
        {
            $dataMore = $xml->createElement('report_data_more');
            $dataMore->setAttribute('start', $limit_count);
            $dataMore->setAttribute('count', $limit_count);
            $dataMore->setAttribute('params', http_build_query($params));
            $root->appendChild($dataMore);
        }

        $xsl = dirname(__FILE__) . '/templates/hits.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}


class LoggerModulePopularityHitsMoreReport extends LoggerModulePopularityHitsReportBaseClass implements LoggerReportInterface
{
    public function __construct(LoggerDatabase $database) 
    {
        parent::__construct($database);
    }

    public function GetReport($root, $date1, $date2, $params = false)
    {
        if (!is_array($params) || !isset($params['start']))
            return false;

        $limit_start = intval($params['start']);
        $limit_count = 100;

        if (isset($params['count']))
            $limit_count = intval($params['count']);

        $xml = $root->ownerDocument;

        $detectResult = $this->DetectModeReport($date1, $date2, $params);
        if (!is_array($detectResult))
            return false;

        list($reportName, $whereStr) = $detectResult;

        $data = $this->GetData($date1, $date2, $whereStr, $limit_start, $limit_count);

        $this->ProcessData($data, $root);

        $xsl = dirname(__FILE__) . '/templates/hits_more.xsl';
        $pi = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="'.$xsl.'"');
        $xml->insertBefore($pi, $root);
        return true;
    }
}
